package com.tanchengjin.admin.aop.operationLog;

import com.tanchengjin.admin.SystemConstants;
import com.tanchengjin.admin.model.pojo.AdminOperationLog;
import com.tanchengjin.admin.model.pojo.AdminUser;
import com.tanchengjin.admin.service.AdminOperationLogService;
import com.tanchengjin.admin.utils.OperationLogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 操作日志aspect
 * @author tanchengjin
 */
@Aspect
@Component
public class OperationLogAspect {
    private final static Logger logger = LoggerFactory.getLogger(OperationLogAspect.class);

    @Autowired
    private AdminOperationLogService operationLogService;

    @Pointcut("@annotation(com.tanchengjin.admin.aop.operationLog.OperationLog)")
    public void operationPointCut() {

    }

    @AfterReturning(value = "operationPointCut()", returning = "keys")
    public void saveLog(JoinPoint joinPoint, Object keys) {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        AdminOperationLog operationLog = new AdminOperationLog();

        //通过反射获取切面的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperationLog annotation = method.getAnnotation(OperationLog.class);
        if (annotation != null) {
            String a = "";
            Integer aid = 0;
            Object attribute = request.getSession().getAttribute(SystemConstants.adminUserSessionKey);
            if (attribute != null) {
                try {
                    AdminUser attribute1 = (AdminUser) attribute;
                    a = attribute1.getName();
                    aid = attribute1.getId();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            String description = annotation.value();
//            将{}替换为管理员名称
            String replace = description.replace("{}", a);
            operationLog.setDescription(replace);
//            operationLog.setDescription(description);
            operationLog.setOperator(a);
        }
        OperationLogUtil.write(request, operationLog.getDescription());
    }
}
